#!/bin/sh
#
# netopeer.rc: Netopeer init script
# Copyright (c) 2006-2012 CESNET, z.s.p.o.
# Author(s): David Kupka <dkupka@cesnet.cz>
#
# This script is written according to SysV init principles.
#
# To activate this script at the boot time simple copy this file (and
# rename it to 'netopeer' - without any suffix) into the /etc/rc.d/init.d
# directory. Then run chkconfig:
#
#    chkconfig --add netopeer
#
# Output is logged in /var/log/netopeer file.
#
# Two lines below this clause are used by chkconfig(8) to set it to run
# in the boot time. The first of those two lines tells chkconfig what
# runlevels the service should be started in by default, as well as the
# start and stop priority levels. The second line contains a description
# for the service.
#
# chkconfig: 345 50 80
# description: Netopeer startup script

BINDIR="@prefix@/bin/"
LOGFILE="/var/log/netopeer"
NETOPEER=netopeer-server

#include functions
. /etc/init.d/functions

case "$1" in
start )
	echo "== Starting Netopeer ==" >> $LOGFILE
	date >> $LOGFILE

	if [ `ps -C netopeer-server | wc -l` -eq 2 ]; then
		echo "Failed: Netopeer is already running." >> $LOGFILE;
		failure; echo "Netopeer is already running.";
		exit 1;
	fi

	$BINDIR$NETOPEER -d

	# for server to start
	sleep 5;

	if [ `ps -C netopeer-server | wc -l` -lt 2 ]; then
		echo "Failure: Netopeer failed to start." >> $LOGFILE;
		failure; echo "Netopeer failed to start.";
		exit 1;
	fi

	success; echo "== Netopeer start ==";
	echo "Success: Netopeer started ==" >> $LOGFILE;
	;;

stop )
	echo "== Stopping Netopeer ==" >> $LOGFILE
	date >> $LOGFILE

	if [ `ps -C netopeer-server | wc -l` -lt 2 ]; then
		echo "Failure: Netopeer is not running." >> $LOGFILE;
		failure; echo "Netopeer is not running.";
		exit 1;
	fi

	killall -15 netopeer-server

	sleep 5;

	if [ `ps -C netopeer-server | wc -l` -eq 2 ]; then
		killall -9 netopeer-server
		sleep 1;


		if [ `ps -C netopeer-server | wc -l` -eq 2 ]; then
			echo "Failure: Netopeer is still running." >> $LOGFILE;
			failure; echo "Netopeer is still running.";
			exit 1;
		fi
	fi

	success; echo "== Netopeer stop ==";
	echo "Success: Netopeer stopped ==" >> $LOGFILE;
	;;

restart|reload )
	$0 stop
	$0 start
	;;

status )
	if [ `ps -C netopeer-server | wc -l` -eq 2 ]; then
		echo "Netopeer is running.";
	else
		echo "Netopeer is stopped.";
	fi
	;;
* )
	# Display usage of this script
	echo "Usage: $0 {start|stop|restart|reload|status}"
	;;
esac
